#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QFontDatabase>
#include <QFontInfo>
#include <QFont>
#include <QHostAddress>
#include <QNetworkInterface>
#include <QThread>
#include <QMessageBox>
#include "DatabaseHelper.h"
#include "ModbusHelper.h"
#include "Strategy.h"
#include "ChatService.h"
#ifdef USE_MQTT
#include "MqttHandler.h"
#endif
#include "ModuleHelper.h"
#include "ModbusSlave.h"
#include "Status.h"
#include <QtQuickControls2/QQuickStyle>
#include "config/SettingManager.h"
#include "updater/UpdateChecker.h"
#include <QNetworkAccessManager>
#include <QSslConfiguration>
#include <QDir>


void initializeDatabase() {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("database.db");

    if (!db.open()) {
        qWarning() << "数据库连接失败";
        return;
    }
}
static void setFont(QGuiApplication &app) {
    // 字体文件路径
    QStringList fontFiles = {
        "/fonts/Ubuntu-Light.ttf",
        "/fonts/Ubuntu-Regular.ttf",
        "/fonts/Ubuntu-Medium.ttf",
        "/fonts/Ubuntu-Bold.ttf",
    };
    
    // 加载所有字体文件
    QFontDatabase::removeAllApplicationFonts();
    QString basePath = QCoreApplication::applicationDirPath();
    
    for (const QString &file : fontFiles) {
        QString fontPath = basePath + file;
        int fontId = QFontDatabase::addApplicationFont(fontPath);
        if (fontId == -1) {
            qWarning() << "Failed to load font:" << fontPath;
        }
    }
    
    // 设置默认字体
    QFont font;
    font.setFamily("Ubuntu");
    font.setPixelSize(14);
    font.setWeight(QFont::Light);  // Regular
    app.setFont(font);
    
    // 打印调试信息
    qDebug() << "Font settings:";
    qDebug() << " Family:" << font.family();
    qDebug() << " Weight:" << font.weight();
    
    // 测试不同字重
    QList<QPair<QString, QFont::Weight>> weights = {
        {"Light", QFont::Light},      // 300
        {"Regular", QFont::Normal},    // 400
        {"Medium", QFont::Medium},     // 500
        {"Bold", QFont::Bold},         // 700
    };
    
    qDebug() << "\nTesting weights:";
    for (const auto &w : weights) {
        QFont testFont("Ubuntu");
        testFont.setPixelSize(14);
        testFont.setWeight(w.second);
        QFontInfo info(testFont);
        qDebug() << w.first << ": requested=" << w.second 
                 << ", actual=" << info.weight();
    }
}
QString getLocalIP() {
    QString ipAddress;
    const QHostAddress &localhost = QHostAddress(QHostAddress::LocalHost);
    for (const QHostAddress &address: QNetworkInterface::allAddresses()) {
        if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost) {
            ipAddress = address.toString();
            break;
        }
    }
    return ipAddress;
}
#ifdef USE_MQTT
void mqttInit(QGuiApplication &app, ModbusHelper *modbusHelper)
{
    QThread* mqttThread = new QThread();
    MqttHandler* mqttHandler = new MqttHandler(mqttThread, modbusHelper);
    QObject::connect(mqttThread, &QThread::started, mqttHandler, &MqttHandler::initialize);
    QObject::connect(&app, &QGuiApplication::aboutToQuit, [mqttThread]() {
        if (mqttThread) {
            mqttThread->quit();
            mqttThread->wait();
            mqttThread->deleteLater();
        }
    });
    mqttHandler->moveToThread(mqttThread);
    mqttThread->start();
}
#endif
void registerTypes(QQmlApplicationEngine& engine)
{
    qmlRegisterType<RunStateEnum>("RunStateEnum", 1, 0, "RunStateEnum");
}
int main(int argc, char *argv[]) {
    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
    qputenv("QT_OPENGL", QByteArray("opengl"));
    qputenv("DISPLAY", QByteArray(":0"));
    // qputenv("QT_QPA_PLATFORM", QByteArray("eglfs"));
#ifdef Q_OS_WIN
    // 分配控制台
    AllocConsole();
    // 重定向标准输出到控制台
    freopen("CONOUT$", "w", stdout);
    freopen("CONOUT$", "w", stderr);
#endif

    // 设置组织名称和组织域
    QCoreApplication::setOrganizationName("weishui");
    QCoreApplication::setOrganizationDomain("weishui.com"); 
    QCoreApplication::setApplicationName("weishui");


    QGuiApplication app(argc, argv);
    
    // 设置应用程序版本
    app.setApplicationVersion("1.0.0");
    
    setFont(app);
    initializeDatabase();

    // QQuickStyle::setStyle("Material");  // 强制使用 Material 样式

    DatabaseHelper *dbHelper = new DatabaseHelper(&app);
    QSqlTableModel* model = dbHelper->getModel();

    ModbusHelper *modbusHelper = new ModbusHelper(&app);

    ModbusSlave *modSlave = new ModbusSlave(&app);
#ifdef USE_MQTT
    mqttInit(app, modbusHelper);
#endif


    ModuleHelper *moduleHelper = new ModuleHelper(nullptr, modbusHelper, "NH3_N");
    Strategy *strategy = new Strategy(&app);
    QObject::connect(strategy, &Strategy::executeOperation, moduleHelper, &ModuleHelper::onManualOperation);
    QObject::connect(strategy, &Strategy::stopAll, moduleHelper, &ModuleHelper::stopAll);
    // 创建ChatService实例
    ChatService *chatService = new ChatService(&app);
    // 创建Status实例
    Status &status = Status::instance();
    SettingsManager settingsManager;
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("sqlModel", model);
    engine.rootContext()->setContextProperty("dbHelper", dbHelper);
    engine.rootContext()->setContextProperty("modbusHelper", modbusHelper);
    engine.rootContext()->setContextProperty("modSlave", modSlave);
    engine.rootContext()->setContextProperty("localIP", getLocalIP());
    engine.rootContext()->setContextProperty("moduleHelper", moduleHelper);
    engine.rootContext()->setContextProperty("strategy", strategy);
    engine.rootContext()->setContextProperty("chatService", chatService); // 注册chatService到QML
    engine.rootContext()->setContextProperty("status", &status); // 注册status到QML
    engine.rootContext()->setContextProperty("settingsManager", &settingsManager);
    // 创建更新检查器
    UpdateChecker *checker = new UpdateChecker(&app);
    engine.rootContext()->setContextProperty("updateChecker", checker);
    // 注册数据类型
    registerTypes(engine);
    // const QUrl url(QStringLiteral("qrc:/mainWindow/main.qml"));
    const QUrl url(QStringLiteral("qrc:/test_main.qml"));
    engine.load(url);

    
    // 启动更新检查
    checker->checkForUpdates();

    return app.exec();
}
